﻿/// <reference path="../../../amplify-vsdoc.js" />
/// <reference path="../../../amplify.js" />
YUI.add('editar-representante-estudiante-view', function (Y) {
    'use strict';
    Y.EditarRepresentanteEstudiante = Y.Base.create('EditarRepresentanteEstudiante', Y.View, [], {
        templateIsCharged: false,
        loadTemplate: function () {
            if (this.template == '') {
                var that = this,
                validator = null,
                request = Y.io('/ExcellentProject/scripts/views/seguridades/estudiantes/templates/asistenteAgregarRepresentante.html', {
                    on: {
                        complete: function (id, response) {
                            that.templateIsCharged = true;
                            that.template = response.responseText;
                            that.render();
                        }
                    },
                    failure: function (id, response) {
                        alert(response)
                    }
                })
            }
        },
        events: {
            '.save': {
                click: 'guardarEstudiante'
            },
            '.backEvent': {
                click: 'regresarADatosEstudiante'
            },
            'cancelEvent': {
                click: 'cancelar'
            }
        },

        render: function () {
            this.loadTemplate();
            if (this.templateIsCharged) {
                var contentTemplate = Y.Handlebars.compile(this.template);
                this.get('container').setHTML(contentTemplate(this.get('model').getAttrs()));

            }
            $('#inputNombre').alpha();
            $('#inputApellido').alpha();
            $('#inputDireccion').alphanum();
            $('#inputTelefono').numeric({
                allowMinus: false,
                maxDigits: 10,
            });
        },

        guardarEstudiante: function (ev) {
            var model = this.get('model');

            var requiredMessages = '';

            //validacion de campos requeridos
            if (Y.one('#inputNombre').get('value').trim() == '') {
                Y.one('#nombreRepresentanteGroup').removeClass('has-success')
                Y.one('#nombreRepresentanteGroup').toggleClass('has-error', true)
                requiredMessages = ' - Nombre requerido. Ingrese el nombre correctamente.<br/>';

            } else {
                Y.one('#nombreRepresentanteGroup').removeClass('has-error')
                Y.one('#nombreRepresentanteGroup').toggleClass('has-success', true)
            }

            if (Y.one('#inputApellido').get('value').trim() == '') {
                Y.one('#apellidoRepresentanteGroup').removeClass('has-success')
                Y.one('#apellidoRepresentanteGroup').toggleClass('has-error', true)
                requiredMessages = ' - Apellido requerido. Ingrese el Apellido correctamente.<br/>';

            } else {
                Y.one('#apellidoRepresentanteGroup').removeClass('has-error')
                Y.one('#apellidoRepresentanteGroup').toggleClass('has-success', true)
            }

            if (Y.one('#inputCorreo').get('value').trim() == '' || !validateEmail(Y.one('#inputCorreo').get('value'))) {
                Y.one('#correoRepresentanteGroup').toggleClass('has-success')
                Y.one('#correoRepresentanteGroup').toggleClass('has-error', true)
                requiredMessages += ' - Correo Eléctronico requerido. Ingrese el Correo Eléctronico correctamente.<br/>';

            } else {
                Y.one('#correoRepresentanteGroup').removeClass('has-error')
                Y.one('#correoRepresentanteGroup').toggleClass('has-success', true)
            }

            debugger

            if (requiredMessages != '') {
                bootbox.dialog({
                    message: requiredMessages,
                    title: "Problemas de Validación",
                    show: true,
                    backdrop: true,
                    closeButton: true,
                    animate: true,

                    className: "my-modal",
                    buttons: {
                        success: {
                            label: "Ok",
                            className: "btn btn-info",

                            callback: function () { }
                        }
                    }
                });
                return;
            }

            model.setAttrs({
                Id: Y.one('#id').get('value'),
                Nombre: Y.one('#inputNombre').get('value'),
                Apellido: Y.one('#inputApellido').get('value').trim(),
                Direccion: Y.one('#inputDireccion').get('value').trim(),
                Telefono: Y.one('#inputTelefono').get('value').trim(),
                Correo: Y.one('#inputCorreo').get('value').trim()
            });

            debugger

            var stringifiedModel = Y.JSON.stringify(model);
            amplify.store('representanteModel', stringifiedModel)

            var studentModel = (new Y.Estudiante()).setAttrs(Y.JSON.parse(amplify.store('studentModel')));

            var options = null;

            var that = this, model = model.save(options, function (err, response) {
                if (err != null) {
                    //TODO Handle error
                } else {
                    if (response.responseText) {
                        model.set('Id', Y.JSON.parse(response.responseText).Id);
                        studentModel.set('Representante', model.get('Id'));
                    }
                    if (studentModel.get('Id') != 0)
                        options = { action: 'update', idEst: studentModel.get('Id') };
                    else
                        options = { urlName: 'saveOption' };


                    var those = that, newModel = studentModel.save(options, function (err, response) {
                        if (err != null)
                            bootbox.dialog({
                                message: "Ocurrieron problemas al registrar el estudiante",
                                title: "Problemas al registrar el estudianteErrores",
                                show: true,
                                backdrop: true,
                                closeButton: true,
                                animate: true,

                                className: "my-modal",
                                buttons: {
                                    success: {
                                        label: "Ok",
                                        className: "btn btn-danger",

                                        /**
                                         * @optional Function
                                         * the callback to invoke when this button is clicked
                                         */
                                        callback: function () { }
                                    }
                                }
                            });
                        else {
                            debugger

                            studentModel.set('Id', Y.JSON.parse(response.responseText).Id)
                            amplify.store('studentModel', Y.JSON.stringify(studentModel))

                            bootbox.dialog({
                                message: "<h5>Representante grabado</h5>",
                                title: "Confirmación",
                                show: true,
                                backdrop: true,
                                closeButton: true,
                                animate: true,

                                className: "my-modal",
                                buttons: {
                                    success: {
                                        label: "Ok",
                                        className: "btn btn-success",

                                        callback: function () { }
                                    }
                                }
                            });


                            Y.one('#navigationButton').set('href', '/estudiantes/matriculacion/' + model.get('Id'))
                            Y.one('#navigationButton').simulate("click");
                        }
                    });

                }
            })

            debugger


        },

        regresarADatosEstudiante: function (ev) {
            if (ev.preventDefault)
                ev.preventDefault();
            else
                ev.returnValue = false;
            Y.one('#navigationButton').set('href', '/estudiante/' + this.get('model').get('Id'))
            Y.one('#navigationButton').simulate("click");
        },
        cancelar: function (ev) {
            if (ev.preventDefault)
                ev.preventDefault();
            else
                ev.returnValue = false;
            localStorage.removeItem('studentModel')
            Y.one('#navigationButton').set('href', '/estudiantes')
            Y.one('#navigationButton').simulate("click");
        }
    })

}, '0.0.0.1', { requires: ['view', 'handlebars', 'node', 'event', 'node-event-simulate', 'json-stringify', 'json-parse', 'estudiante-model'] })